package com.rzhd.coursepatriarch.common.utils.permission;

import android.Manifest;
import android.content.Context;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;

import com.yanzhenjie.permission.AndPermission;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author yql
 * @date: 2018/11/30.
 */
public class PermissionElsePhoneUtils {

    private static Boolean mCameraCanUse = true; //缓存上次的查询结果
    private static Camera mCamera = null;

    public static boolean hasPermissions(Context context, List<String> permissionList) {
        for (String string : permissionList) {
            switch (string) {
                case Manifest.permission.CAMERA:
                    if (hasCameraPermissions(context)) {
                        continue;
                    } else {
                        return false;
                    }
                case Manifest.permission.RECORD_AUDIO:
                    if (isHasAudioPermission(context)) {
                        continue;
                    } else {
                        return false;
                    }
            }
        }
        return true;
    }

    /**
     * 检测相机权限
     *
     * @param context
     * @return
     */
    public static boolean hasCameraPermissions(Context context) {
        try {
            if (RomUtils.isOppo() || RomUtils.isVivo()) {
                if (!isCameraCanUse()) {
                    return false;
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (!isHasCameraPermission()) {
                        return false;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return AndPermission.hasPermissions(context, Manifest.permission.CAMERA);
    }

    /**
     * 相机是否可用
     * ps:有些手机即使禁掉拍照权限获取到的camera也不为null（比如魅族，oppoR9s）
     *
     * @return
     */
    public static boolean isCameraCanUse() {
        boolean canUse = true;
        try {
            mCamera = getCamera();
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            canUse = false;
        }
        mCameraCanUse = canUse;
        return canUse;
    }

    /**
     * 是否拿到相机权限
     * ps: vivo ，opo手机不管授权与否都会
     * 返回PackageManager.PERMISSION_GRANTED（已授权）故作特殊处理
     *
     * @return
     */

    public static boolean isHasCameraPermission() {
        Field fieldPassword;
        try {
            mCamera = getCamera();
            //通过反射去拿相机是否获得了权限
            fieldPassword = mCamera.getClass().getDeclaredField("mHasPermission");
            fieldPassword.setAccessible(true);
            Boolean result = (Boolean) fieldPassword.get(mCamera);
            if (mCamera != null) {
                mCamera.release();
            }
            mCamera = null;
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            mCamera = null;
            return true;
        }
    }

    /**
     * 相机是否可使用
     *
     * @return
     */
    public static Boolean getCameraCanUse() {
        return mCameraCanUse;
    }

    /**
     * 获取相机实例
     *
     * @return
     */
    public static Camera getCamera() {
        if (mCamera == null) {
            return Camera.open();
        }
        return mCamera;
    }


    // 音频获取源
    public static int audioSource = MediaRecorder.AudioSource.MIC;
    // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
    public static int sampleRateInHz = 44100;
    // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
    public static int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
    // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
    public static int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    // 缓冲区字节大小
    public static int bufferSizeInBytes = 0;

    /**
     * 判断是是否有录音权限
     */
    public static boolean isHasAudioPermission(final Context context) {
        bufferSizeInBytes = 0;
        bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz,
                channelConfig, audioFormat);
        AudioRecord audioRecord = new AudioRecord(audioSource, sampleRateInHz,
                channelConfig, audioFormat, bufferSizeInBytes);
        //开始录制音频
        try {
            // 防止某些手机崩溃，例如联想
            audioRecord.startRecording();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        /**
         * 根据开始录音判断是否有录音权限
         */
        if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
            return false;
        }
        audioRecord.stop();
        audioRecord.release();
        audioRecord = null;
        return true;
    }




    /**
     * 判断系统权限是否请求成功
     *
     * @param permissions
     * @return
     */
    private boolean isPermissionGranted(List<String> permissions) {
        boolean requestSuccess;
//        for (String string : permissions) {
//            requestSuccess = isPermissionGranted(string);
//            if (!requestSuccess) {
//                return false;
//            }
//        }
        return true;
    }

    /**
     * 判断系统权限是否请求成功
     *
     * @param permissionName
     * @return
     */
//    private boolean isPermissionGranted(String permissionName) {
//        try {
//            Object object = mContext.getSystemService(Context.APP_OPS_SERVICE);
//            if (object == null) {
//                return false;
//            }
//            Class localClass = object.getClass();
//            Class[] arrayOfClass = new Class[3];
//            arrayOfClass[0] = Integer.TYPE;
//            arrayOfClass[1] = Integer.TYPE;
//            arrayOfClass[2] = String.class;
//            Method method = localClass.getMethod("checkOp", arrayOfClass);
//
//            if (method == null) {
//                return false;
//            }
//            Field opPostNotificationValue = localClass.getDeclaredField(permissionName);
//            int value = (int) opPostNotificationValue.get(Integer.class);
//
//            Object[] arrayOfObject = new Object[3];
//            arrayOfObject[0] = Integer.valueOf(value);
//            arrayOfObject[1] = Integer.valueOf(Binder.getCallingUid());
//            arrayOfObject[2] = mContext.getPackageName();
//            int m = ((Integer) method.invoke(object, arrayOfObject)).intValue();
//            return m == AppOpsManager.MODE_ALLOWED;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;



//        if (Build.VERSION.SDK_INT >= 19) {
//            try {
//                AppOpsManager mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
//
//                String pkg = mContext.getApplicationContext().getPackageName();
//
//                int uid = mContext.getApplicationInfo().uid;
//
//                Class appOpsClass = Class.forName(AppOpsManager.class.getName());
//
//                Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
//
//                Field opPostNotificationValue = appOpsClass.getDeclaredField("OP_CAMERA");
//
//                int value = (int) opPostNotificationValue.get(Integer.class);
//                int m = (int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg);
//                return m == AppOpsManager.MODE_ALLOWED;
//            } catch (Throwable e) {
//                e.printStackTrace();
//                return false;
//            }
//        } else {
//            return false;
//        }
//    }

}

